#!/usr/bin/env node

/**
 * 图标生成脚本
 * 从 PNG 图片生成 Electron 应用所需的所有图标格式
 * 
 * 使用方法:
 *   node scripts/generate-icons.js <input-png-path>
 * 
 * 示例:
 *   node scripts/generate-icons.js assets/my-icon.png
 */

import { execSync } from 'child_process'
import { existsSync, readFileSync } from 'fs'
import { join, dirname, resolve } from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = resolve(__dirname, '..')
const buildDir = join(projectRoot, 'build')

// 检查输入文件
const inputPath = process.argv[2]

if (!inputPath) {
  console.error('❌ 错误: 请提供 PNG 图片路径')
  console.log('\n使用方法:')
  console.log('  node scripts/generate-icons.js <input-png-path>')
  console.log('\n示例:')
  console.log('  node scripts/generate-icons.js assets/my-icon.png')
  process.exit(1)
}

const fullInputPath = resolve(projectRoot, inputPath)

if (!existsSync(fullInputPath)) {
  console.error(`❌ 错误: 文件不存在: ${fullInputPath}`)
  process.exit(1)
}

console.log('📦 开始生成图标...')
console.log(`输入文件: ${fullInputPath}`)
console.log(`输出目录: ${buildDir}\n`)

// 确保 build 目录存在
if (!existsSync(buildDir)) {
  const { mkdirSync } = await import('fs')
  mkdirSync(buildDir, { recursive: true })
}

try {
  // 方法 1: 尝试使用 electron-icon-maker
  console.log('🔧 尝试使用 electron-icon-maker...')
  try {
    execSync(`npx electron-icon-maker --input="${fullInputPath}" --output="${buildDir}"`, {
      stdio: 'inherit',
      cwd: projectRoot
    })
    console.log('\n✅ 图标生成成功！')
    console.log('\n生成的文件:')
    console.log(`  - ${join(buildDir, 'icon.ico')} (Windows)`)
    console.log(`  - ${join(buildDir, 'icon.icns')} (macOS)`)
    console.log(`  - ${join(buildDir, 'icon.png')} (Linux)`)
  } catch (error) {
    console.log('⚠️  electron-icon-maker 不可用，使用备用方法...\n')
    throw error
  }
} catch (error) {
  // 备用方法: 直接复制 PNG 文件
  console.log('📋 使用备用方法: 复制 PNG 文件...')
  const { copyFileSync } = await import('fs')
  
  // 复制为 Linux 图标
  const linuxIcon = join(buildDir, 'icon.png')
  copyFileSync(fullInputPath, linuxIcon)
  console.log(`✅ 已创建: ${linuxIcon}`)
  
  console.log('\n⚠️  注意: 需要手动生成 ICO 和 ICNS 文件')
  console.log('\n请使用以下工具:')
  console.log('  - ICO (Windows): https://convertio.co/zh/png-ico/')
  console.log('  - ICNS (macOS): https://cloudconvert.com/png-to-icns')
  console.log('\n或者安装 electron-icon-maker:')
  console.log('  npm install -g electron-icon-maker')
  console.log('  然后重新运行此脚本')
}

